package com.javaspirit.android.diary.dal;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.javaspirit.android.diary.domain.Note;

public class NoteDao {
	
	private Context context;
	private SQLiteDatabase database;
	private DbHelper dbHelper;
	
	public NoteDao(Context context){
		this.context = context;
	}
	
	public NoteDao open(){
		dbHelper = new DbHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}
	
	public void close(){
		dbHelper.close();
	}
	
	public long add(Note note){
		ContentValues contentValues = buildContentValues(note);
		return database.insert(NoteTable.TABLE_NAME, null, contentValues);
	}
	
	private List<Note> getAll(){
		
		Cursor cursor = getAllCursor();
		List<Note> noteList = new ArrayList<Note>();
		int iRow = cursor.getColumnIndex(NoteTable.COLUMN_ID);
		int iNote = cursor.getColumnIndex(NoteTable.COLUMN_NOTE);
		
		for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
			Note note = new Note();
			note.setId(cursor.getLong(iRow));
			note.setNote(cursor.getString(iNote));
			noteList.add(note);
		}
		return noteList;
	}
	
	public Cursor getAllCursor(){
		return database.query(NoteTable.TABLE_NAME, new String[]{NoteTable.COLUMN_ID, NoteTable.COLUMN_NOTE}, null, null, null, null, null);
	}
	
	private ContentValues buildContentValues(Note note){
		ContentValues contentValues = new ContentValues();
		contentValues.put(NoteTable.COLUMN_NOTE, note.getNote());
		return contentValues;
	}
	
}
